#include "MaxMinAI.h"

MaxMinAI::MaxMinAI()
{

}

void MaxMinAI::computerMove()
{
    Step *bestStep = NULL;
    int maxMinValues = INT_MIN; //人下完电脑的最低分中最高的

    clock_t startTime = clock();
    QVector<Step *> steps;
    getAllCanSteps(steps);
    //模拟走棋算出最高分
    while (steps.count()) {
        Step *step = steps.back();
        moveStone(step->fromId, step->rowTo, step->colTo);
        if (step->toId >= 0)
            stones[step->toId].isAlive = false;

//        int tmpScore = calcScore();
        int tmpScore = getMinScore();
//        int tmpScore = negaMax(1);
//        int tmpScore = alphaBeta(maxDep, INT_MIN, INT_MAX);

        //还原
        if (step->toId >= 0)
            stones[step->toId].isAlive = true;
        moveStone(step->fromId, step->rowFrom, step->colFrom);

        if (tmpScore > maxMinValues) {
            maxMinValues = tmpScore;
            if (bestStep)
                delete bestStep;
            bestStep = step;
        } else
            delete step;
        steps.removeLast();
    }
    clock_t endTime = clock();
    qDebug() << "耗时：" << endTime - startTime;

    saveStep(bestStep->fromId, bestStep->rowTo, bestStep->colTo, bestStep->toId);
    if (bestStep->toId >= 0)
        stones[bestStep->toId].isAlive = false;
    moveStone(bestStep->fromId, bestStep->rowTo, bestStep->colTo);
    delete bestStep;
    checkWin();
    update();
}

//站在人方计算，人走完电脑的最低分
int MaxMinAI::getMinScore()
{
    int minScore = INT_MAX; //电脑下完电脑的最高分中最小的，最小化电脑的最大利益
    QVector<Step*> steps;
    getAllCanSteps(steps); //人的所有可走步
    while (steps.count()){
        //试走
        Step *step = steps.back();
        moveStone(step->fromId, step->rowTo, step->colTo);
        if (step->toId >= 0)
            stones[step->toId].isAlive = false;
        int tmpScore = calcScore();
        //还原
        if (step->toId >= 0)
            stones[step->toId].isAlive = true;
        moveStone(step->fromId, step->rowFrom, step->colFrom);

        if (tmpScore < minScore)
            minScore = tmpScore;
        steps.removeLast();
    }
    return minScore;
}
